<template>
  <div class="container">
    <!-- <upload-file ref="uploadEle" :value="init" :remoteFuc='remoteFuc' multiple></upload-file> -->
    <!-- <upload-imgs ref="uploadEle1" :value="initData" :remoteFuc='remoteFuc' multiple></upload-imgs> -->
    <!-- <upload-img></upload-img> -->
    <!-- <el-button @click="on">点我获取图片值</el-button> -->

    <!-- <el-upload ref="upload" action="" list-type="picture-card" :auto-upload="false" :limit="2" :http-request="httpRequest" :on-remove="handleRemove" :on-change="onChange" :before-upload="beforeAvatarUpload" :on-success="handleUploadSuccess" :file-list="fileList">
      <i slot="trigger" class="el-icon-plus"></i>
    </el-upload>
    <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
    <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
    <el-button @click="add"></el-button> -->
    <!-- <el-image style='height: 480px;' :src="'data:image/png;base64,'+file"></el-image> -->
    <div class="clearfix">
      <a-upload action="https://www.mocky.io/v2/5cc8019d300000980a055e76" list-type="picture-card" :file-list="fileList" @preview="handlePreview" @change="handleChange">
        <div v-if="fileList.length < 8">
          <a-icon type="plus" />
          <div class="ant-upload-text">
            Upload
          </div>
        </div>
      </a-upload>
      <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
        <img alt="example" style="width: 100%" :src="previewImage" />
      </a-modal>
    </div>
  </div>
</template>

<script>
import UploadImgs from "@/components/base/upload-image/index";
import UploadImg from "@/components/base/uploadPictures/UploadImg";
import UploadFile from "@/components/base/upload-file/upload-file";
import { client, headers } from "@/model/oss";
import File from "@/model/file";
const initData = [
  {
    // id: '12d3',
    display:
      "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg",
  },
  {
    // id: '17qr',
    display:
      "http://img-home.talelin.com/images/index/Lin_UI_%E5%B0%81%E9%9D%A2.png",
  },
];
export default {
  name: "file",
  components: {
    UploadFile,
    UploadImg,
    UploadImgs,
  },
  data() {
    return {
      file: "",
      file1: "",
      initData: initData,
      init: [],
      fileList: [],
      url: "",
    };
  },
  created() {},

  methods: {
    getBase64URL(pic) {
      const blob = base64ImgtoFile(pic);
      const blobUrl = window.URL.createObjectURL(blob);
      return blobUrl;
    },
    base64ImgtoFile(dataurl, filename = "file") {
      const arr = dataurl.split(",");
      const mime = arr[0].match(/:(.*?);/)[1];
      const suffix = mime.split("/")[1];
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime,
      });
    },
    base64ImgtoFile1(dataurl, filename = "file") {
      //将base64格式分割：['data:image/png;base64','XXXX']
      const arr = dataurl.split(",");
      // .*？ 表示匹配任意字符到下一个符合条件的字符 刚好匹配到：
      // image/png
      const mime = arr[0].match(/:(.*?);/)[1]; //image/png
      //[image,png] 获取图片类型后缀
      const suffix = mime.split("/")[1]; //png
      const bstr = atob(arr[1]); //atob() 方法用于解码使用 base-64 编码的字符串
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime,
      });
    },
    // dataurl转Blob对象
    dataURLtoBlob(dataurl) {
      convertImgToBase64;
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },

    // Blob对象转Base64
    blobToDataURL(blob, callback) {
      let a = new FileReader();
      a.onload = function (e) {
        callback(e.target.result);
      };
      a.readAsDataURL(blob);
    },

    // 转Blob (url)
    getObjectURL(file) {
      var url = null;
      if (window.createObjectURL !== undefined) {
        // basic
        url = window.createObjectURL(file);
      } else if (window.URL !== undefined) {
        // mozilla(firefox)
        url = window.URL.createObjectURL(file);
      } else if (window.webkitURL !== undefined) {
        // webkit or chrome
        url = window.webkitURL.createObjectURL(file);
      }
      return url;
    },

    // Base64转Blob对象
    dataURItoBlob(base64Data) {
      var byteString;
      if (base64Data.split(",")[0].indexOf("base64") >= 0) {
        byteString = atob(base64Data.split(",")[1]);
      } else {
        byteString = unescape(base64Data.split(",")[1]);
        var mimeString = base64Data.split(",")[0].split(":")[1].split(";")[0];
      }
      var ia = new Uint8Array(byteString.length);
      for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }
      return new Blob([ia], { type: mimeString });
    },

    // 网络图片转base64
    convertImgToBase64(url, callback, outputFormat) {
      var canvas = document.createElement("CANVAS"),
        ctx = canvas.getContext("2d"),
        img = new Image();
      img.crossOrigin = "Anonymous";
      img.onload = function () {
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img, 0, 0);
        var dataURL = canvas.toDataURL(outputFormat || "image/png");
        callback.call(this, dataURL);
        canvas = null;
      };
      img.src = url;
    },

    async on() {
      let res = await this.$refs.uploadEle1.getValue();
      console.log(res);
    },
    async remoteFuc(op, cb) {
      let data = {
        file: op,
      };
      // 新建formDate对象
      let formData = new FormData();
      Object.keys(data).forEach((key) => {
        formData.append(key, data[key]);
      });
      console.log("data", data);
      console.log("formData", formData);
      //请求接口
      this.axios({
        headers: {
          contentType: "multipart/form-data", // 需要指定上传的方式
        },
        url: "https://jsonplaceholder.typicode.com/posts/",
        method: "post",
        data: formData,
        timeout: 200000000, // 防止文件过大超时
        onUploadProgress: (progressEvent) => {
          let percent = (progressEvent.loaded / progressEvent.total) * 100 || 0;
          console.log("进度条", percent);
        },
      })
        .then((res) => {
          this.$message.success("图片上传成功");
          let res1 = {
            url: "http://img-home.talelin.com/images/index/Lin_cms_%E5%B0%81%E9%9D%A2.png",
            display:
              "http://img-home.talelin.com/images/index/Lin_cms_%E5%B0%81%E9%9D%A2.png",
          };
          cb && cb(res1);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    onChange(file, fileList) {
      console.log(file, "file", fileList, "Filest");
      this.fileList = fileList;
    },
    handleUploadSuccess(response, file, fileList) {
      console.log(response, file, fileList, "response, file, fileList");
    },
    handleRemove(e, fileList) {
      this.fileList = fileList;
    },
    beforeAvatarUpload(file) {
      // 文件大小校验
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message.error("文件大小不能超过 10M !");
      }
      return isLt2M;
    },
    httpRequest(file) {
      File.bucketUpload(file.file);
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    async add() {
      let r = await File.urlToBase64(this.initData[0].display);
      console.log("r", r);

      let f = await File.base64ToFile(r);
      console.log("f", f);

      // File.getFileFromUrl(this.initData[0].display, "1.png")
      //   .then((res) => {
      //     console.log(res);
      //   })
      //   .catch((err) => {
      //     console.log(err);
      //   });
    },
  },
};
</script>

<style scoped>
</style>
